<template>
  <!-- 
使用说明：
1）、引入category-cascader.vue
2）、语法：<category-cascader :catelogPath.sync="catelogPath"></category-cascader>
    解释：
      catelogPath：指定的值是cascader初始化需要显示的值，应该和父组件的catelogPath绑定;
          由于有sync修饰符，所以cascader路径变化以后自动会修改父的catelogPath，这是结合子组件this.$emit("update:catelogPath",v);做的
      -->
  <div>
    <el-cascader filterable clearable placeholder="试试搜索：手机" v-model="paths" :options="categorys"
      :props="setting"></el-cascader>
  </div>
</template>

<script>
import PubSub from 'pubsub-js';
export default {
  components: {},
  props: {
    catelogPath: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      setting: {
        value: "catId",
        label: "name",
        children: "children"
      },
      categorys: [],
      paths: [] // 将 paths 初始化为一个空数组
    };
  },
  watch: {
    catelogPath: {
      immediate: true,
      handler(newVal) {
        this.paths = newVal || []; // 添加对 undefined 的判断
      }
    },
    paths(newPaths) {
      if (newPaths) {
        this.$emit("update:catelogPath", newPaths);
        if (PubSub && typeof PubSub.publish === 'function') {
          PubSub.publish('catPath', newPaths);
        } else {
          console.warn('PubSub is not defined or publish method is not available.');
        }
      }
    }
  },
  methods: {
    getCategorys() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get"
      }).then(({ data }) => {
        this.categorys = data.data;
      });
    }
  },
  created() {
    this.getCategorys();
  }
};

</script>
<style scoped>
</style>